﻿using Microsoft.AspNetCore.Mvc;
using XYS.Core.Util;
using XYS.Core.Util.Helper;

namespace XYS.Core.Api
{
    /// <summary>
    /// 基础控制器
    /// </summary>
    [ApiController]
    public class BaseController : Controller
    {
        /// <summary>
        /// 获取当前请求的客户端IP地址
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public virtual string GetRemoteIpAddress()
        {
            //解决cdn的ip问题
            var ip = this.Request.Headers["X-Real-IP"].FirstOrDefault(); // 解决 nginx、docker等 获取ip问题
            if (ip.IsNullOrWhiteSpace() || IPAddressHelper.IsPrivateIP(ip))
                ip = this.Request.Headers["X-Forwarded-For"].FirstOrDefault(); // 解决 nginx、docker等 获取ip问题
            if (string.IsNullOrWhiteSpace(ip))
                ip = this.Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            return ip;
        }

    }
}
